package com.example.demo99.Service.Impl;

import com.example.demo99.Entity.DTO.OrderDto;
import com.example.demo99.Entity.Order;

import com.example.demo99.Entity.OrderItem;
import com.example.demo99.Entity.Product;
import com.example.demo99.Entity.OrderLog;
import com.example.demo99.Enums.OrderStatus;
import com.example.demo99.Mapper.OrderLogMapper;
import com.example.demo99.Mapper.OrderMapper;
import com.example.demo99.Mapper.OrderProductMapper;
import com.example.demo99.Mapper.ProductMapper;
import com.example.demo99.Service.OrderService;
import com.example.demo99.Service.PointService;
import com.example.demo99.common.OrderStatusFlow;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderProductMapper orderProductMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private PointService pointService;
    /**
     * 用户下单并发放积分
     */
    @Transactional
    public void createOrderAndGrantPoints(OrderDto dto) {
        Integer userId = dto.getUserId();
        Integer productId = dto.getProductId();
        Integer quantity = dto.getQuantity();

        // 1. 查询商品信息
        Product product = productMapper.findById(productId);
        BigDecimal totalAmount = product.getPrice().multiply(BigDecimal.valueOf(quantity));

        // 2. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setTotalPrice(totalAmount);
        order.setStatus(OrderStatus.valueOf("PENDING_PAYMENT"));
        //定时任务自动取消未支付订单
        order.setCreateTime(LocalDateTime.now());
        orderMapper.insertOrder(order); // 获取 orderId

        Integer orderId = order.getId();

        // 3. 减库存
        productMapper.decreaseStock(productId, quantity);

        // 4. 插入订单商品记录
        orderMapper.insertOrderProduct(orderId, productId, quantity);

        // 5. 添加订单日志（非必须）
        // ✅ 插入日志
        OrderLog log = new OrderLog();
        log.setOrderId(order.getId());
        log.setAction("创建订单");
        log.setChangedAt(LocalDateTime.now());  // 设置当前时间
        log.setChangedBy("系统");  // 假设是系统操作
        orderLogMapper.insertOrderLog(log);  // 插入日志

        // 6. 添加积分（调用积分服务）
        pointService.addPointsAfterOrder(userId, orderId, totalAmount);




    }
    @Transactional // 保证整个方法的事务一致性
    public void saveOrder(Order order) {
        double totalPrice = 0.0;

        // 设置订单状态为 "待支付"
        if (order.getStatus() == null) {
            order.setStatus(OrderStatus.PENDING_PAYMENT); // 设置默认状态
        }

        for (OrderItem item : order.getItems()) {
            Integer productId = item.getProduct().getId();
            Integer quantity = item.getQuantity();

            Product dbProduct = productMapper.findById(productId);
            if (dbProduct == null) {
                throw new RuntimeException("商品不存在: " + productId);
            }

            if (dbProduct.getStock() < quantity) {
                throw new RuntimeException("库存不足，商品ID: " + productId);
            }
            // 减库存
            productMapper.decreaseStock(productId, quantity);

            double itemTotal = dbProduct.getPrice().multiply(new BigDecimal(quantity)).doubleValue();
            totalPrice += itemTotal;

            item.setPrice(dbProduct.getPrice());
        }

        // 设置订单总价
        order.setTotalPrice(BigDecimal.valueOf(totalPrice));
        //定时任务自动取消未支付订单
        if (order.getCreateTime() == null) {
            order.setCreateTime(LocalDateTime.now()); // ✅ 设置下单时间
        }

        // ✅ 只在此处插入订单（确保能获取生成的 ID）
        orderMapper.insertOrder(order);

        // ✅ 插入中间表
        for (OrderItem item : order.getItems()) {
            Integer productId = item.getProduct().getId();
            Integer quantity = item.getQuantity();
            orderMapper.insertOrderProduct(order.getId(), productId, quantity);
        }
       // ✅ 插入日志
        OrderLog log = new OrderLog();
        log.setOrderId(order.getId());
        log.setAction("创建订单");
        log.setChangedAt(LocalDateTime.now());  // 设置当前时间
        log.setChangedBy("系统");  // 假设是系统操作

        orderLogMapper.insertOrderLog(log);  // 插入日志




    }

    @Override
    public List<Order> getAllOrders() {
        return orderMapper.findAllOrders();
    }
    @Override
    public void updateOrderStatus(Integer orderId, OrderStatus newStatus) {
        Order order = orderMapper.findById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }



        // 状态合法性校验（简单示例）
        OrderStatus currentStatus = order.getStatus();
        if (currentStatus == OrderStatus.CANCELED || currentStatus == OrderStatus.COMPLETED) {
            throw new RuntimeException("订单已完成或已取消，无法修改状态");
        }




//        // 校验是否合法流转
//        List<OrderStatus> allowedNext = OrderStatusFlow.FLOW.get(currentStatus);
//        System.out.println(allowedNext);
//        if (allowedNext == null || !allowedNext.contains(newStatus)) {
//            throw new RuntimeException("非法状态流转：" + currentStatus + " → " + newStatus);
//        }

        // 若新旧状态一致，不更新也不报错（可选：记录日志）
        if (currentStatus == newStatus) {
            System.out.println("状态未改变，无需更新");
            return;
        }

        // 状态合法性检查
        if (currentStatus == OrderStatus.CANCELED || currentStatus == OrderStatus.COMPLETED) {
            throw new RuntimeException("订单已完成或已取消，无法修改状态");
        }

        // 合法流转检查
        List<OrderStatus> allowedNext = OrderStatusFlow.FLOW.get(currentStatus);
        if (allowedNext == null || !allowedNext.contains(newStatus)) {
            throw new RuntimeException("非法状态流转：" + currentStatus + " → " + newStatus);
        }

//        // 权限限制
//        if (newStatus == OrderStatus.DELIVERING && !"ADMIN".equals(userRole)) {
//            throw new RuntimeException("只有管理员可以修改为‘配送中’状态");
//        }

        // 更新状态
        order.setStatus(newStatus);
        orderMapper.updateStatus(orderId, newStatus.name());

    }

}